<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="选择收货地址"
        right-arrow
      ></van-nav-bar>
      <van-icon @click="back" class="cross" name="cross" />
    </header>
    <div class="content">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        add-button-text="添加收货地址"
        @add="onAdd"
        @edit="onEdit"
        @select="selectAddress"
      />
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { AddressList, Toast, NavBar, Icon } from 'vant'
import { getAddressData, updateOrderAddress } from '@/api'

Vue.use(AddressList)
Vue.use(NavBar)
Vue.use(Icon)
export default {
  data () {
    return {
      chosenAddressId: '1',
      list: []
    }
  },
  mounted () {
    getAddressData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      console.log(res.data.data)
      const arr = []
      res.data.data.map((item, index) => {
        let str = ''
        // 如果遇到直辖市，省份和城市要保留一个
        if (item.province === item.city) {
          str += item.province
        } else {
          str += item.province + item.city
        }
        str += item.county
        str += item.addressDetail
        arr.push({
          id: item.addressid,
          name: item.name,
          tel: item.tel,
          address: str,
          isDefault: item.isDefault === 1
        })
      })
      this.list = arr
    })
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    onAdd () {
      Toast('新增地址')
      this.$router.push('/addressadd')
    },
    onEdit (item, index) {
      console.log(item.id)
      Toast('编辑地址:' + index)
      this.$router.push({ path: '/addressmodify/' + item.id })
    },
    selectAddress (item, index) {
      const { orderid } = this.$route.query
      console.log(index, item)
      console.log(orderid)
      updateOrderAddress({
        addressid: item.id,
        orderid
      }).then(res => {
        if (res.data.code === '200') {
          this.$router.go(-1)
        }
      })
    }
  }
}
</script>
<style lang="scss">
.body {
  background-color: white;
}
.van-nav-bar {
  position: relative;
}
.cross {
  position: absolute;
  right: 5px;
  top: 8px;
  color: #6e6e6e;
  z-index: 10;
  font-size: 28px;
}
</style>
